package com.ztesoft.zsmart.zcm.dialing.util;

import com.google.common.base.Strings;
import com.ztesoft.zsmart.core.exception.BaseAppException;
import com.ztesoft.zsmart.core.log.ZSmartLogger;
import com.ztesoft.zsmart.zcm.dialing.domain.dto.FastDFSDto;
import com.ztesoft.zsmart.zcm.dialing.domain.vo.ProbeTypeNameVo;
import com.ztesoft.zsmart.zcm.dialing.infrastructure.condition.ConditionService;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zmc on 2018/7/6.
 */

public final class StringUtil {

    private static final ZSmartLogger LOGGER = ZSmartLogger.getLogger(StringUtil.class);

    public static boolean isNotEmpty(String var0) {
        return var0 != null && var0.length() != 0;
    }

    public static String getExceptionString(Exception e) {
        if (null == e || Strings.isNullOrEmpty(e.getMessage())) {
            return "Exception occurs";
        }
        String result = e.getMessage();
        try {
            Throwable cause = e.getCause();
            while (null != cause) {
                if (!Strings.isNullOrEmpty(cause.getMessage())) {
                    result = cause.getMessage();
                }
                cause = cause.getCause();
            }
        }
        catch (Exception e2) {
            LOGGER.error(e2);
        }
        return result;
    }
    public static String getCheckByExpressionResult(Integer type, String data, String validation, Integer option, String fieldName, String comparative, Double max, Double min) {
        Assert.notNull(data, "Missing validation data");
        String expressionField = "";
        if (1 == type) {
            Assert.notNull(option, "Missing option");
            Assert.hasText(fieldName, "Missing fieldName");
            if ("${RESULT}".equals(fieldName)) {
                expressionField = "get(\"$\")";
            }
            else {
                expressionField = "get(\"" + fieldName + "\")";
            }
            if (option >= 8) {
                Assert.notNull(max, "Missing max");
                Assert.notNull(min, "Missing min");
                if (option == 8) {
                    validation = expressionField + " >= " + min + " && " + expressionField + " <= " + max;
                }
                else if (option == 9) {
                    validation = expressionField + " > " + min + " && " + expressionField + " < " + max;
                }
                else if (option == 10) {
                    validation = expressionField + " > " + min + " && " + expressionField + " <= " + max;
                }
                else if (option == 11) {
                    validation = expressionField + " >= " + min + " && " + expressionField + " < " + max;
                }
                else if (option == 12) {
                    validation = expressionField + " <= " + min + " || " + expressionField + " >= " + max;
                }
                else if (option == 13) {
                    validation = expressionField + " < " + min + " || " + expressionField + " > " + max;
                }
                else if (option == 14) {
                    validation = expressionField + " < " + min + " || " + expressionField + " >= " + max;
                }
                else if (option == 15) {
                    validation = expressionField + " <= " + min + " || " + expressionField + " > " + max;
                }
            }
            else if (option == 7) {
                Assert.hasText(comparative, "Missing comparativeString");
                if ("${RESULT}".equals(fieldName)) {
                    expressionField = "(\"$\",\"" + comparative + "\")";
                }
                else {
                    expressionField = "(\"" + fieldName + "\",\"" + comparative + "\")";
                }
                validation = "contains" + expressionField;
            }
            else {
                Assert.notNull(comparative, "Missing comparative");
                if (option == 1) {
                    validation = expressionField + " > " + comparative;
                }
                else if (option == 2) {
                    validation = expressionField + " >= " + comparative;
                }
                else if (option == 3) {
                    validation = expressionField + " < " + comparative;
                }
                else if (option == 4) {
                    validation = expressionField + " <= " + comparative;
                }
                else if (option == 5) {
                    validation = expressionField + " == " + comparative;
                }
                else if (option == 6) {
                    validation = expressionField + " != " + comparative;
                }
            }
        }
        else if (2 == type) {
            Assert.notNull(validation, "Missing validation expression");
        }
        return ConditionService.matchResult(validation, data);
    }

    public static Boolean getCheckByExpression(Integer type, String data, String validation, Integer option, String fieldName, String comparative, Double max, Double min) {
        return Boolean.valueOf(getCheckByExpressionResult(type, data, validation, option, fieldName, comparative, max, min));
    }

    public static List<ProbeTypeNameVo> getProbeTypeVos(List<String> pathList) {
        List<ProbeTypeNameVo> list = new ArrayList<>();
        for (String name : pathList) {
            ProbeTypeNameVo vo = new ProbeTypeNameVo();
            vo.setName(name);
            vo.setValue(name);
            list.add(vo);
        }
        return list;
    }

    public String getName() {
        return this.getClass().toString();
    }

    public static Integer getTimeByString(String time) {
        if (Strings.isNullOrEmpty(time)) {
            return 0;
        }
        int totalTime = 0;
        String[] strings = time.split(":");
        if (strings[0].startsWith("0")) {
            totalTime += Integer.parseInt(String.valueOf(strings[0].charAt(1))) * 3600;
        }
        else {
            totalTime += Integer.parseInt(String.valueOf(strings[0])) * 3600;
        }
        if (strings[1].startsWith("0")) {
            totalTime += Integer.parseInt(String.valueOf(strings[1].charAt(1))) * 60;
        }
        else {
            totalTime += Integer.parseInt(String.valueOf(strings[1])) * 60;
        }
        if (strings[2].startsWith("0")) {
            totalTime += Integer.parseInt(String.valueOf(strings[1].charAt(1)));
        }
        else {
            totalTime += Integer.parseInt(String.valueOf(strings[1]));
        }
        return totalTime;
    }

    public static Object setResultString(Object output) throws BaseAppException {
        try {
            String resultStr = String.valueOf(output);
            if (resultStr.contains("\n")) {
                int index = resultStr.lastIndexOf("\n");
                int length = resultStr.length() - 1;
                if (index == length) {
                    output = resultStr.substring(0, resultStr.lastIndexOf("\n"));
                }
            }
        }
        catch (Exception e) {
            LOGGER.info("format fail");
        }
        try {
            output = new BigDecimal(String.valueOf(output));
        }
        catch (Exception e) {
            LOGGER.info("not number");
        }
        return output;
    }

    public static String getOracleSplitInString(String originString, String symbol) {
        if (Strings.isNullOrEmpty(originString) || Strings.isNullOrEmpty(symbol)) {
            return "";
        }
        StringBuilder buffer = new StringBuilder();
        if (originString.endsWith(symbol)) {
            originString = originString.substring(0, originString.length() - 1);
        }
        String[] strings = originString.split(symbol);
        for (int i = 0; i < strings.length - 1; i++) {
            buffer.append(strings[i]).append("','");
        }
        buffer.append(strings[strings.length - 1]);
        return buffer.toString();
    }

    public static List<FastDFSDto> getFastDFSDtoByResult(String result) {
        List<FastDFSDto> list = new ArrayList<>();
        FastDFSDto dto = new FastDFSDto();
        List<Map<String, Object>> storageMap = new ArrayList<>();
        Map<String, Object> storeMap = new HashMap<>();
        boolean isGroup = false;
        String[] strings = result.split("\n");
        for (String string : strings) {
            if (Strings.isNullOrEmpty(string)) {
                continue;
            }
            if (string.contains("Group")) {
                isGroup = true;
                dto = new FastDFSDto();
                Map<String, Object> groupMap = new HashMap<>();
                dto.setGroupMap(groupMap);
                list.add(dto);
            }
            else if (string.contains("Storage")) {
                isGroup = false;
                List<Map<String, Object>> mapList = dto.getStorageMap();
                if (null == mapList) {
                    storageMap = new ArrayList<>();
                    storeMap = new HashMap<>();
                    storageMap.add(storeMap);
                    dto.setStorageMap(storageMap);
                }
                else {
                    storeMap = new HashMap<>();
                    storageMap.add(storeMap);
                }
            }
            else {
                if (!string.contains("=")) {
                    continue;
                }
                if (isGroup) {
                    String[] splits = string.split("=");
                    Map<String, Object> groupMap = dto.getGroupMap();
                    groupMap.put(splits[0].trim(), null == splits[1] ? "" : splits[1].trim());
                }
                else {
                    String[] splits = string.split("=");
                    storeMap.put(splits[0].trim(), null == splits[1] ? "" : splits[1].trim());
                }
            }
        }
        return list;
    }

    public static Double getSpaceByResultString(String result) {
        String[] strings = result.split("MB");
        if (strings[0].contains(",")) {
            String[] strings1 = strings[0].trim().split(",");
            return Double.valueOf(strings1[0].trim() + strings1[1].trim());
        }
        else {
            return Double.valueOf(strings[0].trim());
        }
    }

    public static List<Map<String, String>> changeMap(String result) {
        List<Map<String, String>> mapList = new ArrayList<>();
        if (Strings.isNullOrEmpty(result)) {
            return mapList;
        }
        String[] list = result.split("\\n");
        for (String s : list) {
            if (s.contains("Offset")) {
                continue;
            }
            try {
                Map<String, String> linuxUse = new HashMap<>();
                String[] str = s.split("\\s+");
                linuxUse.put("topic", str[0]);
                linuxUse.put("broker", str[1]);
                linuxUse.put("qid", str[2]);
                linuxUse.put("broker_offset", str[3]);
                linuxUse.put("consume_offset", str[4]);
                linuxUse.put("client_ip", str[5]);
                linuxUse.put("diff", str[6]);
                mapList.add(linuxUse);
            }
            catch (Exception e) {
                LOGGER.error(e);
            }
        }
        return mapList;
    }


    public static List<Map<String, String>> changeMessageMap(String result) {
        List<Map<String, String>> mapList = new ArrayList<>();
        if (Strings.isNullOrEmpty(result)) {
            return mapList;
        }
        String[] list = result.split("\\n");
        for (String s : list) {
            if (s.contains("Offset")) {
                continue;
            }
            try {
                Map<String, String> linuxUse = new HashMap<>();
                String[] str = s.split("\\s+");
                linuxUse.put("cluster", str[0]);
                linuxUse.put("broker", str[1]);
                linuxUse.put("qid", str[2]);
                linuxUse.put("max_offset", str[4]);
                mapList.add(linuxUse);
            }
            catch (Exception e) {
                LOGGER.error(e);
            }
        }
        return mapList;
    }
}